<?php

/**
 * Partner kereső oldal.
 *
 * @author poli
 */
class PartnerFinderGenerator extends BaseContentGenerator {

	/**
	 * Ezt mutatja éppen
	 * @var array
	 */
	public $tournament;

	/**
	 * Ezt mutatja éppen
	 * @var array
	 */
	public $tournamentType;

	public function PartnerFinderGenerator($context, $generatorId, $iniParams = null, $skipIniParamsUpdateFromRequest = false) {
		parent::BaseContentGenerator("PartnerFinder", $context, $generatorId, $iniParams, $skipIniParamsUpdateFromRequest);
	}

	/**
	 * Mi most használjuk az iniParams tömbünket nagyon is! Úhygogy nosza, dolgozzuk fel
	 * belőle a dolgokat!
	 *
	 * @see site/contentGenerators/BaseContentGenerator#processSavedIniParams()
	 */
	public function processSavedIniParams($savedIniParams) {
		$this->_iniParams = $savedIniParams;
	}

	/**
	 * Hasonló a page enterPage metódusához. Akkor kerül meghívásra, amikor a
	 * content generátor képernyőre kerül először. Azaz: az előző kérésre adott
	 * válaszban még nem ő generálta a content-et
	 *
	 * Itt meg lehet valósítani mindenféle inicializálást, aminek csak egyszer kell
	 * lefutni amíg a generátor aktív.
	 *
	 */
	public function enterContentGenerator() {
		parent::enterContentGenerator();

		$_SESSION['__partnerfinder_invites'] = array();
	}

	/**
	 * Hasonló a page leavePage metódusához. Akkor kerül meghívásra amikor a user
	 * elhagyja a content generátort. Azaz eddig ő generálta a válaszokba a tartalmat, de
	 * most más valaki generálja.
	 *
	 * Itt meg lehet valósítani mindenféle cleanup dolgokat a kilépés kapcsán.
	 */
	public function leaveContentGenerator() {
		parent::leaveContentGenerator();

		unset($_SESSION['__partnerfinder_formdata']);
		unset($_SESSION['__partnerfinder_invites']);
		unset($_SESSION['__partnerfinder_tournament']);
		unset($_SESSION['__partnerfinder_tournamenttype']);
	}

	protected function _init() {
		if (is_null($this->tournament)) {
			$this->tournament = FunctionLibrary::getSessionValue('__partnerfinder_tournament', null);
			$this->tournamentType = FunctionLibrary::getSessionValue('__partnerfinder_tournamenttype', null);
			if (is_null($this->tournament) || is_null($this->tournamentType)) {
				$tournamentId = FunctionLibrary::getGetIntValueSmart("id", null);
				$tournamentTypeId = FunctionLibrary::getGetIntValueSmart("type", null);
				if (!is_null($tournamentId) && !is_null($tournamentTypeId)) {
					try {
						$this->tournament = SiteDBHelper::getTournament($tournamentId, TextHandler::getCurrentLangcode());
						$this->tournamentType = SiteDBHelper::getTournamentType($tournamentTypeId, TextHandler::getCurrentLangcode());
						$_SESSION['__partnerfinder_tournament'] = $this->tournament;
						$_SESSION['__partnerfinder_tournamenttype'] = $this->tournamentType;
					} catch (Exception $e) {
						$this->errorMsg = "failed to read up tournament!";
						Log::error($this->errorMsg);
						MailHelper::sendAdminMail("PartnerFinderGenerator error", $this->errorMsg);
					}
				} else {
					$this->errorMsg = "tournament or tournament type not set!";
					Log::error($this->errorMsg);
				}
			}
		}
	}

	public function serveRequest() {
		parent::serveRequest();

		$this->_init();

		if (is_null($this->tournament) || is_null($this->tournamentType)) {
			$response = null;
			return $response;
		} else {
			SiteBase::addJavascript('site/js/tournamentScripts.js');

			$action = FunctionLibrary::getGetValue('action');
			if($action) {
				$action = 'action_'.$action;
				$this->$action();
			}

			$tpl = BaseContentGenerator::loadTemplateFile("partnerfinder.tpl.html");
			TextHandler::insertTextsIntoTemplate($tpl);
			$tpl->setVariable('app_root_url', APP_ROOT_URL);

			if(!is_null($this->tournament)) {
				$title = TextHandler::getParsedText("pf_title", array("tournament" => $this->tournament['name'], "tournamentType" => $this->tournamentType['name']));
				SiteBase::setPageTitle($title);
				$tpl->setVariable('partnerFinderTitle', $title);
				$tpl->setVariable('partnerFinderLead', TextHandler::getParsedText("pf_lead", array("tournament" => $this->tournament['name'], "tournamentType" => $this->tournamentType['name'])));
				$tpl->setVariable('regFormUrl', HydraLinkProvider::getLink("partnerFinderRegistrationLink"));

				// értékek hibás kitöltés esetén
				$defaultValues = FunctionLibrary::getSessionValue('__partnerfinder_formdata', array('langcode' => TextHandler::getCurrentLangcode()));
				$tpl->setVariable("form_name", (! isset($defaultValues['name'])? '': $defaultValues['name']));
				$tpl->setVariable("form_email", (! isset($defaultValues['email'])? '': $defaultValues['email']));
				$langs = TextHandler::getEnabledLanguages();
				$langSelect = FormUtil::getComboOptionHTMLTagsFromAssociativeArray($langs, $defaultValues['langcode']);
				$tpl->setVariable("form_langcode", $langSelect);
				$tpl->setVariable("form_description", (! isset($defaultValues['description'])? '': $defaultValues['description']));

				$registrations = SiteDBHelper::getPartnerFinderRegistrations($this->tournament['id'], $this->tournamentType['id']);
				if (! empty($registrations)) {
					foreach ($registrations as $registration) {
						$tpl->setCurrentBlock('partner');
						$tpl->setVariable('pf_reg_name', TextHandler::getText('pf_reg_name'));
						$tpl->setVariable('pf_reg_email', TextHandler::getText('pf_reg_email'));
						$tpl->setVariable('pf_reg_description', TextHandler::getText('pf_reg_description'));
						$tpl->setVariable('pf_invite', TextHandler::getText('pf_invite'));
						$tpl->setVariable('gen_sendform', TextHandler::getText('gen_sendform'));
						$tpl->setVariable('id', $registration['id']);
						$tpl->setVariable('name', $registration['name']);
						$tpl->setVariable('description', $registration['description']);
						$tpl->setVariable('inviteLink', HydraLinkProvider::getLink('partnerFinderInviteLink', array('id' => $registration['id'])));
						$tpl->parseCurrentBlock();
					}
				} else {
					$tpl->replaceBlock('partner', '', false);
					$tpl->touchBlock('partner');
				}
			}
			$tpl->setVariable('pf_reg_name', TextHandler::getText('pf_reg_name'));
			$tpl->setVariable('pf_reg_email', TextHandler::getText('pf_reg_email'));
			$tpl->setVariable('pf_reg_langcode', TextHandler::getText('pf_reg_langcode'));
			$tpl->setVariable('pf_reg_description', TextHandler::getText('pf_reg_description'));
			$tpl->setVariable('gen_sendform', TextHandler::getText('gen_sendform'));
			return $tpl->get();
		}
	}

	function action_register() {
		$postData = array(
			'name' => FunctionLibrary::getPostValue('name'),
			'email' => FunctionLibrary::getPostValue('email'),
			'langcode' => FunctionLibrary::getPostValue('langcode'),
			'description' => FunctionLibrary::getPostValue('description')
		);
		$_SESSION['__partnerfinder_formdata'] = $postData;
		$redirectLink = HydraLinkProvider::getLink('partnerFinderLink');

		try {
			$this->checkData($postData);

			// db mentés
			SiteDBHelper::registerPartnerFinder($this->tournament['id'], $this->tournamentType['id'], $postData);
			unset($_SESSION['__partnerfinder_formdata']);

			// email küldés
			$site = SiteHandler::getCurrentSite();
			$variables = array(
				'comp' => $this->tournament['name'],
				'ttype' => $this->tournamentType['name'],
				'siteName' => $site->name
			);

			$recipient = new AlertRecipient();
			$recipient->sendHere = $postData['email'];
			$recipient->langcodes = array($postData['langcode']);
			$recipient->variables = array(
				'name' => $postData['name'],
				'description' => $postData['description']
			);

			AlertHandler::sendEmailAlert('partnerfinder_registration.tpl.email', array($recipient), $variables);

			handleSuccess(TextHandler::getText('pf_success'), $redirectLink);
			exit();
		} catch (ParameterException $e) {
			$errorStrings = $e->getErrors();
		} catch (Exception $e) {
			$logErrorString = "adding partner finder registration failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
		}

		handleError(TextHandler::getParsedText('pf_err', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectLink);
		exit();
	}

	function action_invite() {
		$postData = array(
			'id' => FunctionLibrary::getGetValue('id'),
			'name' => FunctionLibrary::getPostValue('name'),
			'email' => FunctionLibrary::getPostValue('email'),
			'description' => FunctionLibrary::getPostValue('description'),
			// checkCode() miatt
			'langcode' => TextHandler::getCurrentLangcode()
		);
		$_SESSION['__partnerfinder_invites'][$postData['id']] = $postData;
		$redirectLink = HydraLinkProvider::getLink('partnerFinderLink');

		try {
			$this->checkData($postData);

			// db mentés
			$registration = SiteDBHelper::getPartnerFinderRegistration($postData['id']);

			// email küldés
			$site = SiteHandler::getCurrentSite();
			$variables = array(
				'comp' => $this->tournament['name'],
				'ttype' => $this->tournamentType['name'],
				'siteName' => $site->name
			);

			$recipient = new AlertRecipient();
			$recipient->sendHere = $registration['email'];
			$recipient->langcodes = array($registration['langcode']);
			$recipient->variables = array(
				'name' => $registration['name'],
				'inv_name' => $postData['name'],
				'inv_email' => $postData['email'],
				'inv_description' => $postData['description']
			);

			AlertHandler::sendEmailAlert('partnerfinder_check.tpl.email', array($recipient), $variables);
			unset($_SESSION['__partnerfinder_invites'][$postData['id']]);

			handleSuccess(TextHandler::getText('pf_invite_success'), $redirectLink);
			exit();
		} catch (ParameterException $e) {
			$errorStrings = $e->getErrors();
		} catch (Exception $e) {
			$logErrorString = "inviting partner failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
		}

		handleError(TextHandler::getParsedText('pf_err', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectLink);
		exit();
	}

	private function checkData($values) {
		$e = new ParameterException();

		if (empty($values['name'])) {
			$e->addError(TextHandler::getText('pf_err_emptyname'));
		}

		if (empty($values['email'])) {
			$e->addError(TextHandler::getText('pf_err_emptyemail'));
		} else if (! FunctionLibrary::checkEmailSyntax($values['email'])) {
			$e->addError(TextHandler::getText('pf_err_emailformat'));
		}

		if (empty($values['langcode'])) {
			$e->addError(TextHandler::getText('pf_err_langcode'));
		}

		if ($e->hasError()) throw $e;
	}

}
